package cn.kgc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgc.entity.DataDictionary;
import cn.kgc.form.DataDictionaryForm;
import cn.kgc.form.DictItemQueryForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.DataDictionaryService;
import cn.kgc.utils.PagedGridResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dataDictionary")
@Api(tags = "数据字典表模块")
@Validated
@Slf4j
@CrossOrigin
@SuppressWarnings("all")
public class DataDictionaryController {

    @Resource
    private DataDictionaryService dataDictionaryService;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @PostMapping("/backend/getItemsByKeys")
    @ApiOperation(value="根据字典编码查询字典项")
    public GraceJSONResult getItemsByKeys(@RequestBody DictItemQueryForm form){
        CompletableFuture<List<DataDictionary>> future1= CompletableFuture.supplyAsync(()->{
            //获得传入的公司的有数的key
            List<String> advntages= form.getAdvntages();
            // 根据优势key,获得数据字典值。
            return dataDictionaryService.queryDataDictionaryByTypeAndItemKey(advntages);
        },threadPoolTaskExecutor);

        CompletableFuture<List<DataDictionary>> future2= CompletableFuture.supplyAsync(()->{
            // 根据福利待遇key,获得数据字典值。
            List<String> benfits= form.getBenefits();
            return dataDictionaryService.queryDataDictionaryByTypeAndItemKey(benfits);
        },threadPoolTaskExecutor);

        CompletableFuture<List<DataDictionary>> future3= CompletableFuture.supplyAsync(()->{
            //根据薪资福利key,获得数据字典值。
            List<String> bonus=form.getBonus();
            return dataDictionaryService.queryDataDictionaryByTypeAndItemKey(bonus);
        },threadPoolTaskExecutor);

        CompletableFuture<List<DataDictionary>> future4=CompletableFuture.supplyAsync(()->{
            //根据补助津贴key,获得数据字典值。
            List<String> subsidy=form.getSubsidy();
            return dataDictionaryService.queryDataDictionaryByTypeAndItemKey(subsidy);
        },threadPoolTaskExecutor);

        //等待四个异步任务都执行完毕
        CompletableFuture.allOf(future1,future2,future3,future4).join();

        //返回的结果
        Map<String,List<DataDictionary>> map=new HashMap<>();
        try {
            map.put("advntages",future1.get(2, TimeUnit.SECONDS));
            map.put("benefits",future2.get(2, TimeUnit.SECONDS));
            map.put("bonus",future3.get(2, TimeUnit.SECONDS));
            map.put("subsidy",future4.get(2, TimeUnit.SECONDS));
        }  catch (Exception e) {
           return GraceJSONResult.errorMsg("查询公司福利信息失败");
        }
        return GraceJSONResult.ok(map);
    }


    @PostMapping("/app/getDataByCode")
    @ApiOperation(value="根据字典编码查询字典项")
    public GraceJSONResult getDataByCode(String typeCode){
        String userId = JwtInterceptor.userIds.get();
        if(StrUtil.isNotBlank(userId)){
            return GraceJSONResult.ok(
                            dataDictionaryService.queryDataDictionaryByType(typeCode)
                    );
        }
        return GraceJSONResult.errorMsg("您没有权限操作!");
    }

    @PostMapping("/backend/delete")
    @ApiOperation(value = "删除数据字典项")
    public GraceJSONResult delete(String id){
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if(StrUtil.isNotBlank(adminUserId)){
            return GraceJSONResult.ok(dataDictionaryService.deleteById(id));
        }
        return GraceJSONResult.errorMsg("您没有权限操作");
    }

    @PostMapping("/backend/isEnable")
    @ApiOperation(value = "数据字典项的启用和禁用")
    public GraceJSONResult isEnable(String id){
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if(StrUtil.isNotBlank(adminUserId)){
            //获得原来的数据
            DataDictionary dataDictionary = dataDictionaryService.getById(id);
            //如果原来是请用就改为禁用。如果是禁用改为启用。
            int enable= dataDictionary.getEnable()==1?0:1;
            dataDictionary.setEnable((short)enable);
            //更新数据
            dataDictionaryService.updateById(dataDictionary);
            //返回数据
            return GraceJSONResult.ok(dataDictionary);
        }
        return GraceJSONResult.errorMsg("您没有权限操作");
    }


    @PostMapping("/backend/save")
    @ApiOperation(value = "新增数据字典项")
    public GraceJSONResult save(DataDictionaryForm  dataDictionaryForm){
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if(StrUtil.isNotBlank(adminUserId)){
            DataDictionary dataDictionary=new DataDictionary();
            BeanUtil.copyProperties(dataDictionaryForm,dataDictionary);
            return GraceJSONResult.ok(dataDictionaryService.save(dataDictionary));
        }
        return GraceJSONResult.errorMsg("您没有权限操作");
    }

    @PostMapping("/backend/list")
    @ApiOperation(value = "按条件分页查询字典信息")
    public PagedGridResult list(
            @RequestParam(defaultValue = "") String typeName,
            @RequestParam(defaultValue = "") String itemKey,
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize)
    {
        String adminUserId = JwtInterceptor.adminUserIds.get();
        if(StrUtil.isNotBlank(adminUserId)){
            return dataDictionaryService.page(pageIndex,pageSize,typeName,itemKey);
        }
        //如果登录的用户不是后台管理员,返回空的集合
        return new PagedGridResult();
    }
}